package com.xgp.labblog.controller;

import com.xgp.labblog.model.Speak;
import com.xgp.labblog.model.Writes;
import com.xgp.labblog.service.SpeakService;
import com.xgp.labblog.service.WriteService;
import com.xgp.labblog.tool.BadWordUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class detailsController {

    @Autowired
    WriteService writeService;

    @Autowired
    SpeakService speakService;

    @GetMapping("/writeDetails/{id}")
    public String writeDetails(@PathVariable(name = "id") Integer id, Model model,
                               @RequestParam(value = "title",required=false,defaultValue = "") String title,
                               @RequestParam(value = "text",required=false,defaultValue = "") String text
                               ) {

        try {

            if(!text.isEmpty()) {
                String newText = BadWordUtil2.replaceBadWord(text, 2, "*");
                speakService.addSpeakById(id,newText);
            }

//        Integer wid = Integer.parseInt(id);
            //1,根据文章id查找文章
            Writes write = writeService.FindWriteById(id);

            //2，根据文章id查找评论
            List<Speak> speaks = null;
            if(title.isEmpty()) {
                speaks = speakService.findSpeakByWid(id);
            }else  {
                speaks = speakService.findSpeakByWidAndTitle(id,title);
            }

            if(write == null) {
                return "error/4xx";
            }

            write.setReadcount(write.getReadcount()+1);
            writeService.addReadCount(write);

            //4,加入到model中
            model.addAttribute("writeDetails",write);
            model.addAttribute("speakByWid",speaks);

            return "html/details";
        }catch (Exception e) {
            return "error/4xx";
        }

    }

    @GetMapping("/supper-speak/{id}")
    @ResponseBody
    public void supperWrite(@PathVariable(name = "id") Integer id) {

        speakService.addSupCount(id);
    }

}
